//
// TERMSOCK.CPP -- Socket derived from CAsynCAsyncSocket
//

#include "stdafx.h"
#include "Bterm.h"
#include "BtermDoc.h"
#include "termsock.h"
#include "BtermView.h"


#ifdef _DEBUG
#undef THIS_FILE
static char BASED_CODE THIS_FILE[] = __FILE__;
#endif

IMPLEMENT_DYNAMIC(CTermSocket, CAsyncSocket)

CTermSocket::CTermSocket(CBtermView *pView)
{
	cView = pView;
	isSSH = true;
	isFirstTime = true;
}

CTermSocket::~CTermSocket()
{
}


void CTermSocket::OnConnect(int nErrorCode)
{
	if (nErrorCode)
	{
		cView->m_fConnected = FALSE;  

		CString csMsg;
		csMsg.Format ( _T("Connect Failed(): %d"), nErrorCode );
		AfxMessageBox ( csMsg );

	}
	/*
	else
	{
		if(cView->quickDlg.m_AutoLogin){
			cView->DispatchMessage(cView->quickDlg.m_UserName);
			cView->DispatchMessage(L"\r\n");
			cView->DispatchMessage(cView->quickDlg.m_PassWord);
			cView->DispatchMessage(L"\r\n");
		}
		cView->m_fConnected = TRUE;
	}
	*/
}

void CTermSocket::OnSend(int nErrorCode)
{

	CAsyncSocket::OnSend(nErrorCode);
}

void CTermSocket::OnReceive(int nErrorCode)
{

	while(cView->inSolution);
	unsigned char * pTail = cView->m_strLine + cView->nByteReceive;

	int nBytes = cView->cSock->Receive(pTail ,ioBuffSize ); 

	if (nBytes == 0)
	{
		cView->Display("Receive() indicates that socket is closed\r\n");
		return;
	}
	/*
	if(isSSH && isFirstTime){
		isFirstTime = false;
		this->Send("SSH-2.0-1.0.0(BTERM)\n",21);
		return;
	}
	*/
	if(nBytes != SOCKET_ERROR) 
	{ 
		cView->OnReceive(nBytes);
	}
}

void CTermSocket::OnClose(int nErrorCode)
{

	CAsyncSocket::OnClose(nErrorCode);
	if(!IsWindow(cView->m_hWnd)) return;
	if(!IsWindowVisible(cView->m_hWnd)) return;

	cView->m_fConnected = FALSE;  
	cView->Display("\t Connect Closed(): %d \r\n", nErrorCode);

	
	CDC* pDC = cView->GetWindowDC();
	cView->ClearWindows(pDC);
	//cView->GetDocument()->OnCloseDocument();
	cView->ReleaseDC(pDC);
}

void CTermSocket::OnOutOfBandData(int nErrorCode) 
{
	ASSERT(FALSE); //Telnet should not have OOB data
	CAsyncSocket::OnOutOfBandData(nErrorCode);
}